package com.mimi.controller;

import com.mimi.config.ProjectUrlConfig;
import com.mimi.constant.CookieConstant;
import com.mimi.constant.RedisConstant;
import com.mimi.dataobject.SellerInfo;
import com.mimi.enums.ResultEnum;
import com.mimi.service.SellerService;
import com.mimi.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author 徐向(Arthur Xu)
 * @Description: 卖家用户
 * @Date: Created in  20:53 2017/10/20
 **/
@Controller
@RequestMapping("/seller")
public class SellerUserController {

    @Autowired
    private SellerService sellerService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid, HttpServletResponse response, Map<String, Object> map) {
        //1.openid去和数据库里的数据匹配
        SellerInfo sellerInfo = sellerService.findSellerInfoByOpenid(openid);
        if (sellerInfo == null) {
            map.put("msg", ResultEnum.LOGIN_FAIL.getMessage());
            map.put("url", "/seller/order/list");
            return new ModelAndView("common/error",map);
        }
        //2.设置token到redis
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;
        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX,token),openid,expire, TimeUnit.SECONDS);
        //3.设置token到cookie
        CookieUtil.set(response, CookieConstant.TOKEN,token,CookieConstant.EXPIRE);
        //redirect 最后用完整的HTTP地址,就是绝对路径,尽量少用相对路径
        return new ModelAndView("redirect:" +projectUrlConfig.getSell()+
                "/seller/order/list");
    }

    @GetMapping("/logout")
    public ModelAndView logout(HttpServletRequest request,HttpServletResponse response,Map<String,Object> map) {
        //1.从cookie里查询
        Cookie cookie =CookieUtil.get(request, CookieConstant.TOKEN);

        //2.清除redis
        if (cookie != null) {
            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
        }
        //3.清楚cookit
        CookieUtil.set(response, CookieConstant.TOKEN, null,0);

        map.put("msg", ResultEnum.LOGIN_SUCCESS.getMessage());
        map.put("url","/seller/order/list");

        return new ModelAndView("common/success", map);
    }
}
